<!-- 张梦莉  2017-11-25 商品规格-->

<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters" @submit.native.prevent>
                <el-form-item>
                    <el-input v-model.trim="filters.option_name" placeholder="规格名称">
                    </el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" v-on:click="getOptionList" icon="el-icon-search">搜索</el-button>
                </el-form-item>
                <!--<el-form-item>-->
                    <!--<el-button type="primary" v-on:click="getParamsList" icon="el-icon-search">查询</el-button>-->
                <!--</el-form-item>-->

              <el-form-item style="float: right;">
                <el-form-item>
                  <el-button type="success" v-on:click="handleRestFilters" icon="el-icon-refresh">重置</el-button>
                </el-form-item>
                <el-form-item>
                  <el-button type="danger" @click="batchStatus" icon="el-icon-delete"
                             :disabled="this.sels.length===0">删除
                  </el-button>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" v-on:click="handleAdd" icon="el-icon-plus">新增</el-button>
                </el-form-item>
              </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="listToString" @selection-change="selsChange" highlight-current-row v-loading="listLoading" style="width: 100%;">
            <el-table-column type="selection" width="55px">
            </el-table-column>
            <el-table-column prop="option_name" label="规格名称" sortable width="200x">
            </el-table-column>
            <el-table-column prop="option_value" label="规格子项">
            </el-table-column>
            <el-table-column label="操作" width="210">
                <template slot-scope="scope">
                    <span class="color-blue pr-3 pointer" @click="handleEdit(scope.row)">编辑</span>
                    <span class="color-blue pointer" @click="deleteOption(scope.row)">删除</span>
                </template>
            </el-table-column>
        </el-table>
        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-pagination layout="total, sizes, prev, pager ,next" :page-size="filters.pageSize"
                           @current-change="handleCurrentChange" @size-change="handleSizeChange" :total="total">
            </el-pagination>

        </el-col>

        <!--编辑界面-->
        <el-dialog title="" :visible.sync="editFormVisible" width="30%" :close-on-click-modal="false">
            <div slot="title" class="dialog-title">编辑规格</div>
            <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
                <el-form-item label="规格名称" prop="option_name">
                    <el-input v-model="editForm.option_name" auto-complete="off" autofocus></el-input>
                </el-form-item>
                <el-form-item label="规格选项" prop="option_value">
                    <el-input type="textarea"  v-model="editForm.option_value" auto-complete="off" autofocus></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="editFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
            </div>
        </el-dialog>

        <!--新增界面-->
        <el-dialog title="" :visible.sync="addFormVisible" width="30%" :close-on-click-modal="false">
            <div slot="title" class="dialog-title">新增规格</div>
            <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
                <el-form-item label="规格名称" prop="option_name">
                    <el-input v-model="addForm.option_name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="规格选项" prop="option_values">
                    <el-input type="textarea" placeholder="选项之间用逗号隔开 例如：红色，蓝色，白色" v-model="addForm.option_values" auto-complete="off"></el-input>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false; $refs['addForm'].resetFields()">取消</el-button>
                <el-button :disabled="addDisabled" type="primary" @click.native="addSubmit" :loading="addLoading">保存</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>
  import {getProductOptions, editProductOptions, addProductOptions, deleteProductOption, manyDeleteOptions, checkOptionName} from '../../api/api';

  export default {
    data () {
      return {
        filters: {
          pageSize: 10,
          option_name: '',
          page: 1
        },
        option_id: null,
        optionList: [],   // 商品规格集合
        sels: [], // 列表选中列
        ids: [], // 列表选中项ids
        total: 0,
        listLoading: false,
        editFormVisible: false,  // 编辑界面是否显示
        editLoading: false,
        editFormRules: {
          option_name: [
            {required: true, message: '请输入规格名称', trigger: 'blur'}
          ],
          option_value: [
            {required: true, message: '请输入规格选项', trigger: 'blur'}
          ]
        },
         // 编辑界面数据
        editForm: {
          option_id: null,
          option_name: '',
          option_value: []

        },
        addFormVisible: false,  // 新增界面是否显示
        addLoading: false,
        addDisabled: false,
        addFormRules: {
          option_name: [
            {required: true, message: '请输入规格名称', trigger: 'blur'},
            {
              validator: (rules, value, callback) => {
                let para = {};
                para.value = value;
                checkOptionName(para).then(data => {
                  if (data.status === 1) {
                    callback()
                  } else {
                    callback(new Error('规格名称已存在'))
                  }
                })
              },
              trigger: 'blur'
            }
          ],
          option_values: [
            {required: true, message: '请输入规格选项', trigger: 'blur'}
          ]
        },
        // 新增界面数据
        addForm: {
          option_id: null,
          option_name: '',
          option_value: ''
        },
        timeout: null

      }
    },
    computed: {
      listToString: function () {
        for (let i = 0; i < this.optionList.length; i++) {
          this.optionList[i].option_value = JSON.parse(this.optionList[i].option_value).toString();
        }
        return this.optionList;
      }
    },
    methods: {
      selsChange (sels) {
        this.ids = [];
        this.sels = sels;
        for (let i = 0; i < sels.length; i++) {
          this.ids.push(JSON.stringify(this.sels[i].option_id));
        }
      },
      // 批量删除
      batchStatus () {
        this.$confirm('确认删除选中规格吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          // NProgress.start();
          let para = {};
          console.log(para);
          para.ids = this.ids;
          manyDeleteOptions(para).then((res) => {
            this.listLoading = false;
            // NProgress.done();
            if (parseInt(res.status) === 1) {
              this.$message({
                message: '删除成功',
                type: 'success'
              });
            } else {
              this.$alert('删除失败', '失败', {type: 'error'});
            }
            this.getOptionList();
          });
        }).catch(() => {
        });
      },
      // 搜索重置
      handleRestFilters () {
        this.filters = {
          pageSize: 10,
          option_name: '',
          page: 1
        };
        this.getOptionList()
      },
      // 字符分割
      stringSplit (strings) {
        strings = strings.replace(/，/g, ',');
        let arr = [];
        arr = strings.split(',');
        let arrOptions = [];
        for (let i = 0; i < arr.length; i++) {
          if (arrOptions.indexOf(arr[i]) === -1) {
            arrOptions.push(arr[i]);
          }
        }
        return arrOptions;
      },
      handleCurrentChange (val) {
        this.filters.page = val;
        this.getOptionList();
      },
      // 条数改变
      handleSizeChange (size) {
        this.filters.pageSize = size;
        this.getOptionList();
      },
      // 获取服务器列表
      getOptionList () {
        this.listLoading = true;
        getProductOptions(this.filters).then((res) => {
          this.total = res.totalCount;
          this.optionList = res.data;
          this.listLoading = false;
        });
      },
      // 显示编辑界面
      handleEdit (row) {
        this.editFormVisible = true;
        this.editForm = Object.assign({}, row);
        this.editForm.option_value = JSON.parse(this.editForm.option_value);
      },
      // 显示新增界面
      handleAdd () {
        this.addFormVisible = true;
        this.addDisabled = false;
      },
      // 编辑
      editSubmit () {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.editLoading = true;
              this.editForm.option_value = JSON.stringify(this.stringSplit(this.editForm.option_value));
              editProductOptions(this.editForm).then((res) => {
                this.editLoading = false;
                // NProgress.done();
                if (parseInt(res.status) === 1) {
                  this.$message({
                    message: '提交成功',
                    type: 'success'
                  });
                } else {
                  this.$alert('编辑失败', '失败', {type: 'error'});
                }
                this.$refs['editForm'].resetFields();
                this.getOptionList();
              });
              this.editFormVisible = false;
            });
          }
        });
      },
      // 新增
      addSubmit () {
        this.addDisabled = true;
        this.$refs.addForm.validate((valid) => {
          if (valid) {
            this.addLoading = true
            this.addForm.option_value = JSON.stringify(this.stringSplit(this.addForm.option_values));
            addProductOptions(this.addForm).then((res) => {
              if (parseInt(res.status) === 1) {
                this.addLoading = false;
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
              } else {
                this.$alert('添加失败', '失败', {type: 'error'});
              }
              this.$refs['addForm'].resetFields();
              this.addFormVisible = false;
              this.getOptionList();
            });
          } else {
            this.addDisabled = false
          }
        })
      },
      deleteOption (row) {
        this.$confirm('确定要删除<' + row.option_name + '>吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteProductOption(row.option_id).then(res => {
            if (parseInt(res.status) === 1) {
              this.getOptionList();
              this.$message({
                message: '删除成功',
                type: 'success'
              });
            } else {
              this.$alert('删除失败', '失败', {type: 'error'});
            }
          })
        })
      }
    },
    mounted () {
      this.getOptionList();
    },
    watch: {}
  }
</script>
<style rel='stylesheet/sass' lang='sass' scoped=''>
    /*.click-detail*/
        /*color: #409EFF*/
        /*cursor : pointer*/
    /*.click-detail:hover*/
        /*color: #443dff*/
</style>
